using MediatR;
using S.O.Api.Read.Application.Command.Medical;
using S.O.Domain.Dto.Output;
using S.O.Domain.Medical;
using S.O.ErrorCode;
using S.O.Interstructrue.Base;

namespace S.O.Api.Read.Application.Handler.Medical
{
    /// <summary>
    /// 根据患者ID获取挂号记录列表处理器
    /// 供患者端使用，查看自己的挂号历史和当前挂号状态
    /// </summary>
    public class GetRegistrationByPatientHandler : IRequestHandler<GetRegistrationByPatientCommand, APIPaging<GetRegistrationListDto>>
    {
        /// <summary>
        /// 挂号记录仓储
        /// </summary>
        private readonly IBaseRepository<RegistrationModel> _registrationRepository;

        /// <summary>
        /// 构造函数，通过依赖注入初始化所需服务
        /// </summary>
        /// <param name="registrationRepository">挂号记录仓储</param>
        public GetRegistrationByPatientHandler(IBaseRepository<RegistrationModel> registrationRepository)
        {
            _registrationRepository = registrationRepository;
        }

        /// <summary>
        /// 处理根据患者ID获取挂号记录列表命令
        /// </summary>
        /// <param name="request">查询命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>分页的挂号记录列表</returns>
        public async Task<APIPaging<GetRegistrationListDto>> Handle(GetRegistrationByPatientCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 构建查询条件
                var query = _registrationRepository.GetALL()
                    .Where(r => r.IsEnable && r.PatientId == request.PatientId);
                
                // 如果指定了状态，按状态筛选
                if (!string.IsNullOrEmpty(request.Status))
                {
                    query = query.Where(r => r.Status == request.Status);
                }
                
                // 如果指定了开始日期，按开始日期筛选
                if (request.StartDate.HasValue)
                {
                    query = query.Where(r => r.VisitDate.Date >= request.StartDate.Value.Date);
                }
                
                // 如果指定了结束日期，按结束日期筛选
                if (request.EndDate.HasValue)
                {
                    query = query.Where(r => r.VisitDate.Date <= request.EndDate.Value.Date);
                }
                
                // 按挂号时间倒序排序（最新的在前面）
                query = query.OrderByDescending(r => r.RegistrationDate);
                
                // 执行分页查询
                var totalCount = query.Count();
                var items = query.Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .ToList();
                
                // 转换为DTO
                var dtoList = items.Select(r => new GetRegistrationListDto
                {
                    Id = r.Id,
                    RegistrationNo = r.RegistrationNo,
                    CardNo = r.CardNo,
                    PatientName = r.PatientName,
                    RegistrationType = r.RegistrationType,
                    RegistrationFee = r.RegistrationFee,
                    OtherFee = r.OtherFee,
                    Department = r.Department,
                    Doctor = r.Doctor,
                    RegistrationDate = r.RegistrationDate,
                    VisitDate = r.VisitDate,
                    Status = r.Status,
                    IsEnable = r.IsEnable
                }).ToList();
                
                return new APIPaging<GetRegistrationListDto>
                {
                    PageDatas = dtoList,
                    TotalCount = totalCount
                };
            }
            catch (Exception ex)
            {
                // 返回空结果，避免异常
                return new APIPaging<GetRegistrationListDto>
                {
                    PageDatas = new List<GetRegistrationListDto>(),
                    TotalCount = 0
                };
            }
        }
    }
}